const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const userCollection = db.collection('user')
const selectedStockCollection = db.collection('selectedStock')

// 登录
async function login(event, context) {
  const { phone } = event
  const wxContext = cloud.getWXContext()
  const { OPENID, APPID } = wxContext // Get OPENID and APPID from wxContext
  
  // 检查是否成功获取OPENID
  if (!OPENID) {
    return {
      success: false,
      message: '获取用户openid失败'
    }
  }

  try {
    // 查找用户是否存在
    const user = await userCollection.where({
      phone: phone
    }).get()
    
    if (user.data.length === 0) {
      // 新用户，创建记录
      await userCollection.add({
        data: {
          phone,
          openid: OPENID,
          appid: APPID,
          session_key: event.session_key || '', // session_key 客户端可能不直接提供，可以先留空或通过其他方式获取
          loginStatus: 1,
          createTime: db.serverDate()
        }
      })
    } else {
      // 更新用户信息
      await userCollection.where({
        phone: phone
      }).update({
        data: {
          openid: OPENID,
          appid: APPID,
          session_key: event.session_key || '', // session_key 客户端可能不直接提供
          loginStatus: 1,
          updateTime: db.serverDate()
        }
      })
    }
    
    return {
      success: true,
      message: '登录成功',
      openid: OPENID // 确保这里正确返回OPENID
    }
  } catch (error) {
    return {
      success: false,
      message: error.message
    }
  }
}

// 退出登录
async function logout(event, context) {
  const { phone } = event
  const wxContext = cloud.getWXContext()
  const { OPENID } = wxContext // Get OPENID from wxContext
  
  try {
    await userCollection.where({
      phone: phone,
      openid: OPENID // 确保是当前用户的退出操作
    }).update({
      data: {
        loginStatus: 0,
        updateTime: db.serverDate()
      }
    })
    
    return {
      success: true,
      message: '退出登录成功'
    }
  } catch (error) {
    return {
      success: false,
      message: error.message
    }
  }
}

// 检查登录状态
async function checkLoginStatus(event, context) {
  const { phone } = event
  const wxContext = cloud.getWXContext()
  const { OPENID } = wxContext // Get OPENID from wxContext
  
  try {
    const user = await userCollection.where({
      phone: phone,
      openid: OPENID // 确保检查的是当前用户的状态
    }).get()
    
    if (user.data.length === 0) {
      return {
        success: false,
        message: '用户不存在或openid不匹配'
      }
    }
    
    return {
      success: true,
      isLoggedIn: user.data[0].loginStatus === 1,
      userInfo: user.data[0]
    }
  } catch (error) {
    return {
      success: false,
      message: error.message
    }
  }
}

// 添加自选股
async function addSelectedStock(event, context) {
  const { stockCode } = event
  const wxContext = cloud.getWXContext()
  const { OPENID } = wxContext

  if (!OPENID) {
    return { success: false, message: '获取用户openid失败' }
  }

  try {
    // 查找用户是否已有自选记录
    const userSelected = await selectedStockCollection.where({
      user_openid: OPENID
    }).get()

    if (userSelected.data.length === 0) {
      // 用户第一次添加自选，创建新记录
      await selectedStockCollection.add({
        data: {
          user_openid: OPENID,
          stock_codes: [stockCode],
          createTime: db.serverDate()
        }
      })
    } else {
      // 用户已有自选记录，更新自选股数组
      const existingCodes = userSelected.data[0].stock_codes || []
      if (!existingCodes.includes(stockCode)) {
        await selectedStockCollection.doc(userSelected.data[0]._id).update({
          data: {
            stock_codes: db.command.push(stockCode),
            updateTime: db.serverDate()
          }
        })
      }
    }

    return { success: true, message: '添加自选成功' }
  } catch (error) {
    return { success: false, message: error.message }
  }
}

// 移除自选股
async function removeSelectedStock(event, context) {
  const { stockCode } = event
  const wxContext = cloud.getWXContext()
  const { OPENID } = wxContext

  if (!OPENID) {
    return { success: false, message: '获取用户openid失败' }
  }

  try {
    // 查找用户自选记录
    const userSelected = await selectedStockCollection.where({
      user_openid: OPENID
    }).get()

    if (userSelected.data.length > 0) {
      const existingCodes = userSelected.data[0].stock_codes || []
      const newCodes = existingCodes.filter(code => code !== stockCode)

      await selectedStockCollection.doc(userSelected.data[0]._id).update({
        data: {
          stock_codes: newCodes,
          updateTime: db.serverDate()
        }
      })
    }

    return { success: true, message: '移除自选成功' }
  } catch (error) {
    return { success: false, message: error.message }
  }
}

// 获取用户自选股列表
async function getUserSelectedStocks(event, context) {
  const wxContext = cloud.getWXContext()
  const { OPENID } = wxContext

  if (!OPENID) {
    return { success: false, message: '获取用户openid失败' }
  }

  try {
    const userSelected = await selectedStockCollection.where({
      user_openid: OPENID
    }).get()

    if (userSelected.data.length > 0) {
      return { success: true, stockCodes: userSelected.data[0].stock_codes || [] }
    } else {
      return { success: true, stockCodes: [] }
    }
  } catch (error) {
    return { success: false, message: error.message }
  }
}

// 云函数入口函数
exports.main = async (event, context) => {
  const { type } = event
  
  switch (type) {
    case 'login':
      return await login(event, context)
    case 'logout':
      return await logout(event, context)
    case 'checkStatus':
      return await checkLoginStatus(event, context)
    case 'addSelectedStock':
      return await addSelectedStock(event, context)
    case 'removeSelectedStock':
      return await removeSelectedStock(event, context)
    case 'getUserSelectedStocks':
      return await getUserSelectedStocks(event, context)
    default:
      return {
        success: false,
        message: '未知的操作类型'
      }
  }
} 